package kitwee.com.kanpad.orderDetail;

import android.content.Context;
import android.os.CountDownTimer;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.kitwee.serialport.util.SimpleCountDownTimer;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;

import kitwee.com.kanpad.DaoManager;
import kitwee.com.kanpad.SocketDataDaoUtil;
import kitwee.com.kanpad.bean.SocketPortData;
import kitwee.com.kanpad.bean.SocketUploadPortData;
import okhttp3.Call;
import utils.DeviceUtils;
import utils.LinkedHashSetBlockingQueue;
import utils.SPUtils;

/**
 * Socket 记录
 * Created by ganquan on 2019/4/2 20:12
 */
public class ServerSocetReporter {
    private RetransmissionThread mRetransmissionThread;
    private Timer mIntervalTimer;
    //    private CountDownTimer mDataTimeout;
    // 存储数据上报时间间隔(单位：秒)
    private static final int PERSISTENCE_PERIOD = 60;
    private static final ServerSocetReporter INSTANCE = new ServerSocetReporter();
    private SocketDataDaoUtil socketDataDaoUtil;
    private String format1;

    private ServerSocetReporter() {
    }

    public static ServerSocetReporter getInstance() {
        return INSTANCE;
    }

    private Context  mContext ;
    public void initialize(Context context) {
        LogUtils.e("ServerSocetReporter ： 初始化");
        socketDataDaoUtil = new SocketDataDaoUtil(context);
        initializeTimer();
        mRetransmissionThread = new RetransmissionThread();
        mRetransmissionThread.start();
        this.mContext=context;

    }

    private void initializeTimer() {
        mIntervalTimer = new Timer(true);
//        mIntervalTimer.scheduleAtFixedRate(new TimerTask() {
//            @Override
//            public void run() {
//
//                reportPersistentData();
//            }
//        }, PERSISTENCE_PERIOD * 1000, PERSISTENCE_PERIOD * 1000); // 存储数据上报
//
//        mDataTimeout = new SimpleCountDownTimer(60_000) {
//            @Override
//            public void onTick(long l) {
//                super.onTick(l);
//                LogUtils.e("上报数据 ： onTick" + l / 1000);
//            }
//
//            @Override
//            public void onFinish() {
//                mCurrData = null;
//                LogUtils.e("上报数据 ： onFinish");
//            }
//        }; // 60秒内，若实时数据未更新，则判定设备离线

        mIntervalTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                scanSerialPortDatabase();
                LogUtils.e("扫描重传数据库 ： ");
            }
        }, 3_000,  30 * 1000); // 扫描重传数据库
//        }, 3_000, 15 * 60 * 1000); // 扫描重传数据库
    }

    /**
     * 重传线程
     */
    private class RetransmissionThread extends Thread {

        @Override
        public void run() {
            while (!isInterrupted()) {
                if (mCurrData == null)
                    return;
                retransmissionData(mCurrData);
                try {
                    sleep(1_500); // 1.5秒之后重传下一条数据
                } catch (InterruptedException e) {
                    // do nothing
                }
            }
        }
    }

    /**
     * 重传数据
     */
    private void retransmissionData(List<SocketPortData> returnMap) {
        LogUtils.e("重传数据");
        reportData(returnMap,  true);
    }

    private List<SocketPortData> mCurrData = null;
    private List<SocketUploadPortData> mUpLoadData = new ArrayList<>();

    private void reportData(final List<SocketPortData> data, boolean retransmission) {
        mUpLoadData.clear();

        if (data == null) {
            return;
        }

        for(SocketPortData socketPortData : data){
            mUpLoadData.add(new SocketUploadPortData(socketPortData.getParameterKey(),socketPortData.getParameterValue()
            ,socketPortData.getParameterUnit()));
        }


        if (retransmission ) {
//            mCurrData = data; // 实时数据
            format1= utils.SPUtils.getString(mContext,"formatDate");
        }else{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date date = new Date();
            format1 = format.format(date);
        }
        mCurrData = data; // 实时数据
        String yunPaiId = SerialPortPreferences.getDeviceId();
        String timeSpa = SerialPortPreferences.getTimeSpa();
        String uploadUrl = SerialPortPreferences.getUploadUrl();
        if(TextUtils.isEmpty(yunPaiId)||TextUtils.isEmpty(uploadUrl)||TextUtils.isEmpty(timeSpa)){
            socketDataDaoUtil.deleteAll();
            socketDataDaoUtil.insertMultSocket(data);
            LogUtils.e("请前往配置页配置参数。");
            ToastUtils.showShort("请前往配置页配置参数。");
            return;
        }
        String str = JSON.toJSONString(mUpLoadData);
        LogUtils.e("上报数据 ;SocketPortData ：" + str);
        OkHttpUtils.post()
                .url(uploadUrl)
//                .url("http://localhost:9999/SOS.MES/JiangHuBll/InsertMachineData")
                .addParams("Machine", yunPaiId)
                .addParams("Date", format1)
                .addParams("TokenID", "00418834439B45568B97E06976221F0F")
                .addParams("DataJson", str)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                LogUtils.e("上传失败 : " +e.getMessage());
                socketDataDaoUtil.deleteAll();
                socketDataDaoUtil.insertMultSocket(data);
                SPUtils.putString(mContext,"formatDate", format1);
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.e("上传成功");
                socketDataDaoUtil.deleteAll();
            }
        });
    }


    /**
     * 扫描数据库以重传
     */
    private void scanSerialPortDatabase() {
        LogUtils.e("扫描数据库以重传");
        List<SocketPortData> failedData = socketDataDaoUtil.queryAll();
        if (failedData == null || failedData.isEmpty()) {
            LogUtils.e("没有查询到需要重传的数据");
            return;
        }
        SocketPortData tempData;
        for (int i = 0; i < failedData.size(); i++) {
            tempData = failedData.get(i);
        }
        reportData(failedData,  true);
    }

    /**
     * 上报实时数据
     */
    public void reportRealTimeData(boolean paused, List<SocketPortData> data) {
        LogUtils.e("上报实时数据");
        mCurrData = data;
        reportData(mCurrData,  false);
    }

    /**
     * 取消初始化上传服务
     */
    public void deinitialize() {
        if (mIntervalTimer != null) {
            mIntervalTimer.cancel();
        }
        if (mRetransmissionThread != null) {
            mRetransmissionThread.interrupt();
        }
    }
}
